<template>
  <!-- 多账号设置 -->
  <Top-Page class="multi-account-box">
    <NavBar title="多账号设置" leftArrow :rightText="rightText" @click-left="navBack()" @click-right="onClickRight" />

    <view class="accounts-box">
      <view
        class="accounts-item border-bottom-after"
        v-for="(item, index) in accountList"
        :key="item"
        @click.stop="changeCard(index)"
      >
        <view class="accounts-item__left-del" v-show="delShow" @click.stop="delShowModal(index)"></view>

        <image class="accounts-item__avatar" :src="item.avatar" mode="aspectFill" />

        <view class="accounts-item__content">
          <view class="accounts-item__content-name">
            {{ item.realname }}
          </view>

          <view class="accounts-item__content-idCard">
            {{ item.account }}
          </view>
        </view>

        <view :class="['accounts-item__right', item.activity && !delShow ? 'checkmark' : '']"></view>
      </view>

      <view class="accounts-item border-bottom-after" v-show="!delShow && more">
        <view class="accounts-item__avatar close-css_icon close-zhen"></view>

        <view class="accounts-item__content" @click.stop="toLogin">添加或注册账号</view>
      </view>
    </view>

    <view class="quit-btn" v-show="!delShow" @tap="logout()">退出登录</view>
  </Top-Page>
</template>

<script>
import NavBar from '@/components/NavBar/NavBar.vue';
import { navBack } from '@/utils/utils.js';

import { useloginStore } from '@/store/login';
import pinia from '@/store/index';
const loginStore = useloginStore(pinia);
export default {
  data() {
    return {
      navBack: navBack,
      delShow: false,
      more: true,
      rightText: '编辑',
      accountList: {}
    };
  },
  components: { NavBar },
  created() {
    this.firstApi();
  },
  methods: {
    //切换账号
    changeCard(key) {
      // 检查当前选中的元素的 activity 是否已经是 true
      if (this.accountList[key].activity) return;

      // 遍历 accountList 数组，直接修改元素的 activity 属性

      const keys = Object.keys(this.accountList);
      this.changeLogin(keys, key);
    },
    //切换账号登录
    changeLogin(keys, key) {
      const client_id = uni.getStorageSync('client_id');
      const data = {
        client_id: client_id,
        code: '',
        rememberMe: false,
        token: key
      };

      this.$api.LoginApi.userchange(data).then((res) => {
        console.log(res);
        if (res.code == 0) {
          //切换视图样式
          keys.forEach((k) => {
            this.accountList[k].activity = k === key ? true : false;
          });

          const token = res.data.token;
          uni.setStorageSync('authToken', res.data.authToken);
          uni.setStorageSync('Token', token);

          //多账户
          let newUserData = {};
          newUserData[token] = res.data.userInfo;

          const existingData = JSON.parse(uni.getStorageSync('multiAccounts') || '{}');
          const newData = Object.assign(this.addOrUpdateUserData(existingData, newUserData, res.data.userInfo.user_id));

          uni.setStorageSync('multiAccounts', JSON.stringify(newData));

          let userInfo = res.data.userInfo;

          // 登录成功后绑定wss
          this.socketIo.send({
            type: 'bindUid',
            user_id: userInfo.user_id,
            token: res.data.authToken
          });

          console.log(userInfo, '重登');

          loginStore.login(userInfo);
          uni.reLaunch({
            url: '/pages/index/index'
          });
          setTimeout(() => {
            this.$router.go(0);
          }, 100);
        }
      });
    },
    addOrUpdateUserData(existingData, newUserData, userId) {
      // 遍历现有的对象，查找是否有相同的 user_id
      for (const key in existingData) {
        if (existingData[key].user_id === userId) {
          console.log(existingData[key].user_id, userId);
          delete existingData[key];
        }
      }

      return Object.assign(existingData, newUserData);
    },
    //删除账号
    delShowModal(key) {
      const userInfo = uni.getStorageSync('userInfo');
      uni.showModal({
        title: '警告',
        content: `确认删除账号${userInfo.account}吗？`,
        showCancel: true,
        success: (res) => {
          if (res.confirm) {
            this.del(key);
          } else if (res.cancel) {
          }
        }
      });
    },
    del(key) {
      // // 获取要删除的元素的 activity 状态
      const wasActive = this.accountList[key].activity === true;

      // // 删除指定元素
      delete this.accountList[key];
      uni.setStorageSync('multiAccounts', JSON.stringify(this.accountList));

      // 如果删除的数据有 `activity` 为 `true`
      if (wasActive) {
        // const keys = Object.keys(this.accountList);
        // keys.length && (this.accountList[keys[0]].activity = true);
        this.toLogin();
      } else {
        this.delStorage(key);
      }
    },
    onClickRight() {
      this.delShow = !this.delShow;

      this.rightText = this.delShow ? '完成' : '编辑';
    },
    firstApi() {
      const multiAccounts = JSON.parse(uni.getStorageSync('multiAccounts') || '{}');
      const length = Object.keys(multiAccounts).length;
      const userInfo = uni.getStorageSync('userInfo');

      this.more = length < 10 ? true : false;

      for (const key in multiAccounts) {
        if (multiAccounts[key].user_id === userInfo.user_id) {
          multiAccounts[key].activity = true;
        } else {
          multiAccounts[key].activity = false;
        }
      }

      Object.assign(this.accountList, multiAccounts);
    },
    toLogin() {
      uni.reLaunch({
        url: '/pages/login/index'
      });
    },
    //删除指定账号的信息
    delStorage(key) {
      const token = uni.getStorageSync('Token');
      delete this.accountList[token];
      uni.setStorageSync('multiAccounts', JSON.stringify(this.accountList));

      key === token && uni.removeStorageSync('Token');
    },
    logout() {
      let client_id = uni.getStorageSync('client_id');
      this.$api.LoginApi.logout({ client_id: client_id }).then((res) => {
        if (res.code == 0) {
          const token = uni.getStorageSync('Token');
          this.delStorage(token);

          loginStore.logout();
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.multi-account-box {
  min-height: 100vh;
  line-height: 1;
  padding: 100rpx 20rpx;

  .checkmark {
    position: relative;
    width: 24rpx;
    height: 12rpx;
    border-left: 1rpx solid #38b7f1;
    border-bottom: 1rpx solid #38b7f1;
    transform: rotate(-45deg);
  }

  .nav-bar {
    background-color: transparent;
  }

  .accounts-box {
    width: 100%;
    margin-top: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fff;
    border-radius: 20rpx;

    .accounts-item {
      width: 100%;
      height: 100rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 0 32rpx;

      .accounts-item__left-del {
        position: relative;
        width: 40rpx;
        height: 40rpx;
        margin-right: 20rpx;
        font-weight: bold;
        background-color: #ff3f3f;
        border-radius: 50%;

        &::after {
          content: ' ';
          position: absolute;
          top: 18rpx;
          left: 10rpx;
          width: 20rpx;
          height: 4rpx;
          background-color: #fff;
        }
      }

      .accounts-item__avatar {
        width: 2rem;
        height: 2rem;
        border-radius: 50%;
        flex-shrink: 0;
      }

      .close-zhen {
        transform: rotate(-45deg);
        background-color: #efefef;

        &::after,
        &::before {
          background-color: #cecece;
        }
      }

      .accounts-item__content {
        flex: 1;
        padding: 0 20rpx;
        font-weight: bold;
        color: #333;

        .accounts-item__content-idCard {
          color: #ccc;
          font-size: 12rpx;
          margin-top: 6rpx;
          font-weight: 100;
        }
      }

      .accounts-item__right {
        flex-shrink: 0;
      }
    }
  }

  .quit-btn {
    width: 100%;
    margin-top: 20rpx;
    border-radius: 20rpx;
    padding: 0 32rpx;
    height: 100rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    background-color: #fff;
    font-weight: bold;
  }
}
</style>
